//
//  ZoomingScrollView.m
//  MWPhotoBrowser
//
//  Created by Michael Waterfall on 14/10/2010.
//  Copyright 2010 d3i. All rights reserved.
//

#import "MWZoomingScrollView.h"
#import "MWPhotoBrowser.h"
#import "MWPhoto.h"
//#import "IIIBaseData.h"


#import "SDImageCache.h"
// Declare private methods of browser
@interface MWPhotoBrowser ()
- (UIImage *)imageForPhoto:(id<MWPhoto>)photo;
- (void)cancelControlHiding;
- (void)hideControlsAfterDelay;
@end

// Private methods and properties
@interface MWZoomingScrollView ()
@property (nonatomic, assign) MWPhotoBrowser *photoBrowser;
- (void)handleSingleTap:(CGPoint)touchPoint;
- (void)handleDoubleTap:(CGPoint)touchPoint;
@end

@implementation MWZoomingScrollView

@synthesize photoBrowser = _photoBrowser, photo = _photo, captionView = _captionView;

//修改：yinlinlin
@synthesize hidePlayBu = _hidePlayBu;
@synthesize playSoundBu = _playSoundBu;
@synthesize playImg = _playImg;
//修改完成

- (id)initWithPhotoBrowser:(MWPhotoBrowser *)browser {
    if ((self = [super init])) {
        _hidePlayBu = YES;
        _hideSoundPlay = YES;
        // Delegate
        self.photoBrowser = browser;
        
		// Tap view for background
		_tapView = [[MWTapDetectingView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
		_tapView.tapDelegate = self;
		_tapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
		_tapView.backgroundColor = [UIColor blackColor];
		[self addSubview:_tapView];
		
		// Image view
		_photoImageView = [[MWTapDetectingImageView alloc] initWithFrame:CGRectZero];
		_photoImageView.tapDelegate = self;
		_photoImageView.contentMode = UIViewContentModeCenter;
		_photoImageView.backgroundColor = [UIColor blackColor];
		[self addSubview:_photoImageView];
		
		// Spinner
		_spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
		_spinner.hidesWhenStopped = YES;
		_spinner.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin |
        UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin;
		[self addSubview:_spinner];
		
        //修改：yinlinlin,添加播放按钮
        _playBu = [UIButton buttonWithType:UIButtonTypeCustom];
        [_playBu setFrame:CGRectMake(100, 200, 96, 96 )];
        [_playBu setTitle:@"播放" forState:UIControlStateNormal];
        [_playBu setImage:[UIImage imageNamed:@"album_videoplay.png"] forState:UIControlStateNormal];
        [self addSubview:_playBu];
        
        
        [_playBu addTarget:self action:@selector(playVideo) forControlEvents:UIControlEventTouchUpInside];
        
        //语音播放按钮
        _playSoundBu = [UIButton buttonWithType:UIButtonTypeCustom];
//        [_playSoundBu setImageEdgeInsets:UIEdgeInsetsMake(28, 1.5, 28, 1.5)];
        [_playSoundBu setBackgroundImage:[UIImage imageNamed:@"album_playSound.png"] forState:UIControlStateNormal];
        [_playSoundBu setFrame:CGRectMake(101.5, 200, 97, 40)];
        [_playSoundBu setTitleEdgeInsets:UIEdgeInsetsMake(30, 31.5, 30, 3)];
        [_playSoundBu setTitle:@"6''" forState:UIControlStateNormal];
        [_playSoundBu setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//        [_playSoundBu setTitle:@"语音播放" forState:UIControlStateNormal];
//        [_playSoundBu setImage:[UIImage imageNamed:@"album_videoplay.png"] forState:UIControlStateNormal];
        [self addSubview:_playSoundBu];
        [_playSoundBu addTarget:self action:@selector(playPhotoSound:) forControlEvents:UIControlEventTouchUpInside];
        _playImg = [[UIImageView alloc]initWithFrame:CGRectMake(15, 6, 28, 28)];
        _playImg.image = [UIImage imageNamed:@"广播3.png"];
        [_playSoundBu addSubview:_playImg];
        
        NSArray *animationImages = animationImages = [NSArray arrayWithObjects:@"广播1.png",@"广播2.png",@"广播3.png", nil];
        NSMutableArray *images = [NSMutableArray arrayWithCapacity:3];
        for(NSString *path in animationImages)
        {
            [images addObject:[UIImage imageNamed:path]];
        }
        _playImg.animationImages = images;
        _playImg.animationDuration = 1.0;
        [_playImg release];
//        [images release];
        //修改完成
        
		// Setup
		self.backgroundColor = [UIColor blackColor];
		self.delegate = self;
		self.showsHorizontalScrollIndicator = NO;
		self.showsVerticalScrollIndicator = NO;
		self.decelerationRate = UIScrollViewDecelerationRateFast;
		self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        
    }
    return self;
}

/**
 * @函数名称：playVideo
 * @函数描述：点击播放按钮，将事件通过回调传到控制界面
 * @输入参数：void
 * @输出参数：void
 * @返回值：void
 * @author：yinlinlin
 */
- (void)playVideo
{
    if (_playPressedCallBack)
    {
        _playPressedCallBack(YES);
    }
}

- (void)playPhotoSound:(UIButton *)sender
{
    if ([sender isSelected])
    {
        [sender setSelected:NO];
    }
    else
        [sender setSelected:YES];
    if (_playPressedCallBack)
    {
        _playPressedCallBack([sender isSelected]);
    }
    
}
- (void)dealloc {
	[_tapView release];
	[_photoImageView release];
	[_spinner release];
    [_photo release];
    [_captionView release];
	[super dealloc];
}

- (void)setPhoto:(id<MWPhoto>)photo {
    _photoImageView.image = nil; // Release image
    if (_photo != photo) {
        [_photo release];
        _photo = [photo retain];
    }
    [self displayImage];
}

- (void)prepareForReuse {
    self.photo = nil;
    [_captionView removeFromSuperview];
    self.captionView = nil;
}

#pragma mark - Image

// Get and display image
- (void)displayImage {
	if (_photo && _photoImageView.image == nil) {
        
		//修改：yinlinlin
        [_playBu setHidden:YES];
        [_playSoundBu setHidden:YES];
        //修改完成
        
		// Reset
		self.maximumZoomScale = 1;
		self.minimumZoomScale = 1;
		self.zoomScale = 1;
		self.contentSize = CGSizeMake(0, 0);
		
		// Get image from browser as it handles ordering of fetching
		UIImage *img = [self.photoBrowser imageForPhoto:_photo];
		if (img) {
			//修改：yinlinlin
            if (!_hidePlayBu) {
                [_playBu setHidden:NO];
            }
            else if (!_hideSoundPlay)
            {
                [_playSoundBu setHidden:NO];
                [_playSoundBu setSelected:NO];
            }
            //修改完成

            
			// Hide spinner
			[_spinner stopAnimating];
			
			// Set image
            //**********************************************************
            //如果委托对象为相册 则需对图片进行解密处理、、相对应在展示的时候需要进行加密  解密在- (void)handleMWPhotoLoadingDidEndNotification:(NSNotification *)notification 方法中进行  目标方法在MWPhotoBrowser中。视频加载为小图 不进行加密 相应跳过解密

    
//            if([self.photoBrowser.delegate isKindOfClass:[BanBu_AlbumDisplayViewController class]])
//            {
//                IIIBaseData *b =[AlbumManager.photosArray objectAtIndex: ([(self) tag] - 1000)];
//                if([b.web_url_big length]&&![b.web_url_big hasSuffix:@".mp4"])
//                {
//                    NSString *imgPath = [[SDImageCache sharedImageCache] cachePathForKey:[[AlbumManager.photosArray objectAtIndex: ([(self) tag] - 1000)] web_url_big]];
//                    img = [BanBu_AddMosaicsViewController decryptImagePath:imgPath];
//                }
//            }
//         
            //************************************************************
            //************************************************************

            MWPhoto *p = [MWPhoto photoWithImage:img];
            [_photoBrowser.photos replaceObjectAtIndex:[(self) tag] - 1000 withObject:p];
			_photoImageView.image = img;
			_photoImageView.hidden = NO;
			
			// Setup photo frame
			CGRect photoImageViewFrame;
			photoImageViewFrame.origin = CGPointZero;
			photoImageViewFrame.size = img.size;
			_photoImageView.frame = photoImageViewFrame;
			self.contentSize = photoImageViewFrame.size;

			// Set zoom to minimum zoom
			[self setMaxMinZoomScalesForCurrentBounds];
			
		} else {
			
			// Hide image view
			_photoImageView.hidden = YES;
			[_spinner startAnimating];
			
		}
		[self setNeedsLayout];
	}
}

// Image failed so just show black!
- (void)displayImageFailure {
	[_spinner stopAnimating];
}

#pragma mark - Setup

- (void)setMaxMinZoomScalesForCurrentBounds {
	
	// Reset
	self.maximumZoomScale = 1;
	self.minimumZoomScale = 1;
	self.zoomScale = 1;
	
	// Bail
	if (_photoImageView.image == nil) return;
	
	// Sizes
    CGSize boundsSize = self.bounds.size;
    CGSize imageSize = _photoImageView.frame.size;
    
    // Calculate Min
    CGFloat xScale = boundsSize.width / imageSize.width;    // the scale needed to perfectly fit the image width-wise
    CGFloat yScale = boundsSize.height / imageSize.height;  // the scale needed to perfectly fit the image height-wise
    CGFloat minScale = MIN(xScale, yScale);                 // use minimum of these to allow the image to become fully visible
	
	// If image is smaller than the screen then ensure we show it at
	// min scale of 1
	if (xScale > 1 && yScale > 1) {
		minScale = 1.0;
	}
    
	// Calculate Max
	CGFloat maxScale = 2.0; // Allow double scale
    // on high resolution screens we have double the pixel density, so we will be seeing every pixel if we limit the
    // maximum zoom scale to 0.5.
	if ([UIScreen instancesRespondToSelector:@selector(scale)]) {
		maxScale = maxScale / [[UIScreen mainScreen] scale];
	}
	
	// Set
	self.maximumZoomScale = maxScale;
	self.minimumZoomScale = minScale;
	self.zoomScale = minScale;
    if(self.maximumZoomScale ==1)
    {
        self.maximumZoomScale =2;
    }

	// Reset position
	_photoImageView.frame = CGRectMake(0, 0, _photoImageView.frame.size.width, _photoImageView.frame.size.height);
	[self setNeedsLayout];

}

#pragma mark - Layout

- (void)layoutSubviews {
	
	// Update tap view frame
	_tapView.frame = [[UIScreen mainScreen] bounds];
	
	// Spinner
	if (!_spinner.hidden) _spinner.center = CGPointMake(floorf(self.bounds.size.width/2.0),
													  floorf(self.bounds.size.height/2.0));
	// Super
	[super layoutSubviews];
	
    // Center the image as it becomes smaller than the size of the screen
    CGSize boundsSize = [[UIScreen mainScreen] bounds].size;
    CGRect frameToCenter = _photoImageView.frame;
    
    // Horizontally
    if (frameToCenter.size.width < boundsSize.width) {
        frameToCenter.origin.x = floorf((boundsSize.width - frameToCenter.size.width) / 2.0);
	} else {
        frameToCenter.origin.x = 0;
	}
    
    // Vertically
    if (frameToCenter.size.height < boundsSize.height) {
        frameToCenter.origin.y = floorf((boundsSize.height - frameToCenter.size.height) / 2.0);
	} else {
        frameToCenter.origin.y = 0;
	}
    
	// Center
	if (!CGRectEqualToRect(_photoImageView.frame, frameToCenter))
		_photoImageView.frame = frameToCenter;
	
}

#pragma mark - UIScrollViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
	return _photoImageView;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
	[_photoBrowser cancelControlHiding];
}

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view {
	[_photoBrowser cancelControlHiding];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
	[_photoBrowser hideControlsAfterDelay];
}

#pragma mark - Tap Detection

- (void)handleSingleTap:(CGPoint)touchPoint {
	[_photoBrowser performSelector:@selector(toggleControls) withObject:nil afterDelay:0.2];
}

- (void)handleDoubleTap:(CGPoint)touchPoint {
	
	// Cancel any single tap handling
	[NSObject cancelPreviousPerformRequestsWithTarget:_photoBrowser];
	
	// Zoom
	if (self.zoomScale == self.maximumZoomScale) {
		
		// Zoom out
		[self setZoomScale:self.minimumZoomScale animated:YES];
		
	} else {
		
		// Zoom in
		[self zoomToRect:CGRectMake(touchPoint.x, touchPoint.y, 1, 1) animated:YES];
		
	}
	
	// Delay controls
	[_photoBrowser hideControlsAfterDelay];
	
}

// Image View
- (void)imageView:(UIImageView *)imageView singleTapDetected:(UITouch *)touch { 
    [self handleSingleTap:[touch locationInView:imageView]];
}
- (void)imageView:(UIImageView *)imageView doubleTapDetected:(UITouch *)touch {
    [self handleDoubleTap:[touch locationInView:imageView]];
}

// Background View
- (void)view:(UIView *)view singleTapDetected:(UITouch *)touch {
    [self handleSingleTap:[touch locationInView:view]];
}
- (void)view:(UIView *)view doubleTapDetected:(UITouch *)touch {
    [self handleDoubleTap:[touch locationInView:view]];
}

@end
